<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222"><meta name="generator" content="Hexo 6.3.0">

  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css" integrity="sha256-AbA177XfpSnFEvgpYu1jMygiLabzPCJCRIBtR5jGc0k=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.1.1/animate.min.css" integrity="sha256-PR7ttpcvz8qrF57fur/yAx1qXMFJeJFiA6pSzWi0OIE=" crossorigin="anonymous">

<script class="next-config" data-name="main" type="application/json">{"hostname":"fengxun2017.github.io","root":"/","images":"/images","scheme":"Muse","darkmode":false,"version":"8.13.2","exturl":false,"sidebar":{"position":"right","display":"hide","padding":18,"offset":12},"copycode":{"enable":false,"style":null},"bookmark":{"enable":false,"color":"#222","save":"auto"},"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"stickytabs":false,"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"}}</script><script src="/js/config.js"></script>

    <meta name="description" content="stream buffer 是一种轻量级的数据流传递方式，通过限制只有一个写，并且也只有一个读，使得内部实现逻辑更高效，并且由于只有一个读和一个写，内部实现中需要保护的临界区“很小”，这些都提高了stream buffer传递数据的效率。">
<meta property="og:type" content="article">
<meta property="og:title" content="FreeRTOS-stream buffer">
<meta property="og:url" content="http://fengxun2017.github.io/2023/02/22/FreeRTOS-stream-buffer/index.html">
<meta property="og:site_name" content="fx">
<meta property="og:description" content="stream buffer 是一种轻量级的数据流传递方式，通过限制只有一个写，并且也只有一个读，使得内部实现逻辑更高效，并且由于只有一个读和一个写，内部实现中需要保护的临界区“很小”，这些都提高了stream buffer传递数据的效率。">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="http://fengxun2017.github.io/2023/02/22/FreeRTOS-stream-buffer/readable-writeable.png">
<meta property="article:published_time" content="2023-02-21T16:00:00.000Z">
<meta property="article:modified_time" content="2023-03-11T07:12:31.297Z">
<meta property="article:author" content="feng xun">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://fengxun2017.github.io/2023/02/22/FreeRTOS-stream-buffer/readable-writeable.png">


<link rel="canonical" href="http://fengxun2017.github.io/2023/02/22/FreeRTOS-stream-buffer/">



<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"zh-CN","comments":true,"permalink":"http://fengxun2017.github.io/2023/02/22/FreeRTOS-stream-buffer/","path":"2023/02/22/FreeRTOS-stream-buffer/","title":"FreeRTOS-stream buffer"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>FreeRTOS-stream buffer | fx</title>
  






  <script async defer data-website-id="" src=""></script>

  <script defer data-domain="" src=""></script>

  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>
  <a target="_blank" rel="noopener" href="https://github.com/fengxun2017" class="github-corner" aria-label="View source on GitHub"><svg width="80" height="80" viewBox="0 0 250 250" style="fill:#70B7FD; color:#fff; position: absolute; top: 0; border: 0; right: 0;" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a><style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style>
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <p class="site-title">fx</p>
      <i class="logo-line"></i>
    </a>
      <p class="site-subtitle" itemprop="description">FreeRTOS交流QQ群-663806972 BLE学习交流群-498676838</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu"><li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a></li><li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a></li>
  </ul>
</nav>




</div>
        
  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-overview-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">feng xun</p>
  <div class="site-description" itemprop="description">FreeRTOS交流QQ群-663806972 BLE学习交流群-498676838</div>
</div>
<div class="site-state-wrap site-overview-item animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/archives/">
          <span class="site-state-item-count">96</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
          <a href="/categories/">
        <span class="site-state-item-count">16</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
  </nav>
</div>
  <div class="cc-license site-overview-item animated" itemprop="license">
    <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh" class="cc-opacity" rel="noopener" target="_blank"><img src="https://cdnjs.cloudflare.com/ajax/libs/creativecommons-vocabulary/2020.11.3/assets/license_badges/small/by_nc_sa.svg" alt="Creative Commons"></a>
  </div>



        </div>
      </div>
    </div>
  </aside>
  <div class="sidebar-dimmer"></div>


    </header>

    
  <div class="back-to-top" role="button" aria-label="返回顶部">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://fengxun2017.github.io/2023/02/22/FreeRTOS-stream-buffer/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="feng xun">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="fx">
      <meta itemprop="description" content="FreeRTOS交流QQ群-663806972 BLE学习交流群-498676838">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="FreeRTOS-stream buffer | fx">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          FreeRTOS-stream buffer
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2023-02-22 00:00:00" itemprop="dateCreated datePublished" datetime="2023-02-22T00:00:00+08:00">2023-02-22</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/FreeRTOS/" itemprop="url" rel="index"><span itemprop="name">FreeRTOS</span></a>
        </span>
    </span>

  
    <span class="post-meta-break"></span>
    <span class="post-meta-item" title="本文字数">
      <span class="post-meta-item-icon">
        <i class="far fa-file-word"></i>
      </span>
      <span class="post-meta-item-text">本文字数：</span>
      <span>5.6k</span>
    </span>
    <span class="post-meta-item" title="阅读时长">
      <span class="post-meta-item-icon">
        <i class="far fa-clock"></i>
      </span>
      <span class="post-meta-item-text">阅读时长 &asymp;</span>
      <span>7 分钟</span>
    </span>
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <center>
stream buffer 是一种轻量级的数据流传递方式，通过限制只有一个写，并且也只有一个读，使得内部实现逻辑更高效，并且由于只有一个读和一个写，内部实现中需要保护的临界区“很小”，这些都提高了stream buffer传递数据的效率。
</center>

<span id="more"></span>

<hr>
<p>当任务间需要传递较多数据时，一般会选择使用消息队列作为消息传递的媒介。FreeRTOS中的消息队列，属于“重资源”，其内部控制复杂占用资源较多。<br>例如，FreeRTOS的消息队列是允许多个任务并发读&#x2F;写，因此，存在写和写的并发访问数据冲突，写和读的并发冲突，以及读和读的并发冲突。所以，其内部的数据读取全部过程都需要放在“临界区”中，数据写入的全部过程也需要放在“临界区”中，从而避免并发的读&#x2F;写冲突。<br>FreeRTOS的消息队列可以参考：<a href="https://fengxun2017.github.io/2022/12/12/FreeRTOS-use-queue/">FreeRTOS-使用消息队列</a>，<a href="https://fengxun2017.github.io/2022/12/08/FreeRTOS-queue-internal-details/">FreeRTOS-消息队列内部细节</a></p>
<p>但实际应用中，大多数时候，我们的应用场景是一个任务&#x2F;中断服务（writer）向另一个任务传递(reader)数据。<br>也就是对于一些数据的传递场景，只存在一个writer负责写入数据（产生数据），也只存在一个reader负责读数据（消费数据）。FreeRTOS针对这种应用场景，提供了<code>stream buffer</code>模块。</p>
<p>由于只能应用于只有一个写和读的场景。因此<code>stream buffer</code>内部实现中不需要考虑写和写的竞争冲突，也不需要考虑读和读的竞争冲突，只需要考虑写和读的竞争冲突即可。所以<code>stream buffer</code>逻辑相对<code>消息队列</code>来说更简洁高效，并且内部的“临界区”也更小。<br>例如，当我们使用<code>stream buffer</code>来发送&#x2F;获取数据时，其内部只在判断可写入的空闲大小&#x2F;可读取的数据量时才需要同时访问<strong>读指针</strong>和<strong>写指针</strong>，如下图所示：<br>蓝色区域为有效数据。<br><strong>Head</strong>：表示可写空间起始位置。<br><strong>Tail</strong>：表示可读数据起始位置。<br><img src="/2023/02/22/FreeRTOS-stream-buffer/readable-writeable.png"></p>
<p>因此，我们的临界区只要保护判断可写&#x2F;可读大小的代码段即可。因为：<br>后续的<strong>写操作</strong>只会访问<strong>Head</strong>指针，而由于只存在<strong>一个写</strong>任务，不存在对<strong>Head</strong>的竞争访问，所以不需要保护。<br>同样，后续的<strong>读操作</strong>只会访问<strong>Tail</strong>指针，而由于只存在<strong>一个读</strong>任务，不存在对<strong>Tail</strong>的竞争访问，所以不需要保护。<br>PS：这里只是举例，<code>stream buffer</code>的实际实现中，判断可写&#x2F;可读大小的代码段同样不需要临界区保护，不过还是存在一个小的临界区用来保护另一段代码，具体可参考文章<a href="https://fengxun2017.github.io/2023/03/04/FreeRTOS-stream-buffer-details/">FreeRTOS-stream buffer内部细节</a>。</p>
<p>综上，<code>stream buffer</code>是FreeRTOS针对 只存在一个写，并且也只存在一个读的场景，提出的一个高效数据流传递方案。这里所说的数据流，是指数据的发送单位是以字节为单位。<br>例如，在文章<a href="https://fengxun2017.github.io/2022/12/12/FreeRTOS-use-queue/">FreeRTOS-使用消息队列</a>中，我们创建消息队列时，就需要指定消息的大小（n字节），后续的每次发送&#x2F;接收消息，都是以该大小为单位的（每次发送&#x2F;接收n字节）。<br>而<code>stream buffer</code>使用的数据流形式，每次发送&#x2F;接收是以字节为单位的。每次可以发送任意字节的数据，也可以接收任意字节的数据。</p>
<p>使用<code>stream buffer</code>需要将源文件<code>stream_buffer.c</code>添加到工程中，并且需要在工程配置文件<code>FreeRTOSConfig.h</code>中添加：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">define</span> configUSE_TASK_NOTIFICATIONS    (1)</span></span><br></pre></td></tr></table></figure>
<p><strong>注意</strong>：<code>stream buffer</code>使用了<a href="https://fengxun2017.github.io/2023/02/07/FreeRTOS-task-notification/">Task Notification</a>的<code>index=0</code>的那个数据，如果你的工程里使用了<code>task notification</code>，需要注意这个问题。</p>
<p>创建一个 stream buffer：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">StreamBufferHandle_t <span class="title function_">xStreamBufferCreate</span><span class="params">( <span class="type">size_t</span> xBufferSizeBytes, <span class="type">size_t</span> xTriggerLevelBytes )</span>;</span><br></pre></td></tr></table></figure>
<ul>
<li>xBufferSizeBytes：这个<code>stream buffer</code>的大小，一共可以缓存多少字节的数据。</li>
<li>xTriggerLevelBytes：当任务从空的<code>stream buffer</code>获取数据时，可以阻塞任务（当设置了超时等待）。之后当某个任务向<code>stream buffer</code>中发送了大于等于<code>xTriggerLevelBytes</code>大小的字节后，就会自动唤醒在该<code>stream buffer</code>上等待数据的任务。<br><strong>注意</strong>：如果等待时间到达设置的超时时间了，任务恢复就绪并运行后，即使buffer中所存的数据还没到xTriggerLevelBytes，任务还是会读取当前已有的数据。</li>
<li>返回值：返回一个可用的<code>stream buffer</code>。</li>
</ul>
<p>向目标<code>stream buffer</code>中发送数据：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">size_t</span> <span class="title function_">xStreamBufferSend</span><span class="params">( StreamBufferHandle_t xStreamBuffer,</span></span><br><span class="line"><span class="params">                          <span class="type">const</span> <span class="type">void</span> *pvTxData,</span></span><br><span class="line"><span class="params">                          <span class="type">size_t</span> xDataLengthBytes,</span></span><br><span class="line"><span class="params">                          TickType_t xTicksToWait )</span>;</span><br></pre></td></tr></table></figure>
<ul>
<li>xStreamBuffer：用来标识目标<code>stream buffer</code></li>
<li>pvTxData：需要发送的数据。</li>
<li>xDataLengthBytes：发送数据的字节大小。</li>
<li>xTicksToWait：如果当前<code>stream buffer</code>中的可写空间不够写入目标字节数据，则等待<code>xTicksToWait</code>设置的超时时间。<strong>注意</strong>：如果超时时间到达了，即使当前<code>stream buffer</code>的可写空间不够写入全部目标数据，该函数仍旧会根据当前可写空间写入尽可能多的数据。</li>
<li>返回值：最终实际写入<code>stream buffer</code>中的数据量。</li>
</ul>
<p>PS：如果数据写入方是中断处理函数，则使用<code>xStreamBufferSendFromISR</code>。数据写入方只能有一个，是一个任务或者是一个中断处理函数。</p>
<p>从目标<code>stream buffer</code>中读取数据：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">size_t</span> <span class="title function_">xStreamBufferReceive</span><span class="params">(StreamBufferHandle_t xStreamBuffer,</span></span><br><span class="line"><span class="params">                            <span class="type">void</span> *pvRxData,</span></span><br><span class="line"><span class="params">                            <span class="type">size_t</span> xBufferLengthBytes,</span></span><br><span class="line"><span class="params">                            TickType_t xTicksToWait )</span>;</span><br></pre></td></tr></table></figure>
<ul>
<li>xStreamBuffer：目标<code>stream buffer</code>。</li>
<li>pvTxData：用来存储读取的数据。</li>
<li>xDataLengthBytes：指明<code>pvTxData</code>所指数组的大小。每次读取，会从<code>stream buffer</code>中读取尽可能多的字节，但不会超过<code>xDataLengthBytes</code>（用来放所读数据的buffer就这么大）。</li>
<li>xTicksToWait：如果当前<code>stream buffer</code>为空，则任务会等待<code>xTicksToWait</code>设置的超时时间。<br>如果超时时间到达前，写任务向<code>stream buffer</code>中发送了大于等于<code>xTriggerLevelBytes</code>字节的数据，会唤醒读任务，（如果读任务可以立刻运行会）读任务会读取尽可能多的数据（不超过<code>xDataLengthBytes</code>）。<br>如果<code>stream buffer</code>中的数据一直小于<code>xTriggerLevelBytes</code>，当超时时间到达后，该函数仍旧会从<code>stream buffer</code>中读取尽可能多的数据。</li>
<li>返回值：最终实际从<code>stream buffer</code>中读取的数据量。</li>
</ul>
<p>PS：如果数据读取方是中断处理函数，则使用<code>xStreamBufferReceiveFromISR</code>。数据读取方只能有一个，是一个任务或者是一个中断处理函数。</p>
<p>一个简单的使用样例： task_a 向 <code>stream buffer</code>写入数据，task_b 从<code>stream buffer</code>中读取数据。</p>
<p>任务代码：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="type">void</span> <span class="title function_">task_a</span><span class="params">( <span class="type">void</span> *pvParameters )</span> &#123;</span><br><span class="line"></span><br><span class="line">    StreamBufferHandle_t sbuffer = (StreamBufferHandle_t)pvParameters;</span><br><span class="line">    <span class="type">char</span> data[<span class="number">9</span>] = &#123;<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>,<span class="number">5</span>,<span class="number">6</span>,<span class="number">7</span>,<span class="number">8</span>,<span class="number">9</span>&#125;;</span><br><span class="line">    <span class="type">int</span> send_len = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">for</span>(;;) &#123;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 每次最多发送 9 字节。</span></span><br><span class="line">        send_len = xStreamBufferSend(sbuffer, data, <span class="number">9</span>, pdMS_TO_TICKS(<span class="number">1000</span>));</span><br><span class="line">        SEGGER_RTT_printf(<span class="number">0</span>, <span class="string">&quot;sent %d bytes!\n&quot;</span>, send_len);</span><br><span class="line"></span><br><span class="line">        vTaskDelay(pdMS_TO_TICKS(<span class="number">1000</span>));</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="type">void</span> <span class="title function_">task_b</span><span class="params">( <span class="type">void</span> *pvParameters )</span> &#123;</span><br><span class="line">    </span><br><span class="line">    StreamBufferHandle_t sbuffer = (StreamBufferHandle_t)pvParameters;</span><br><span class="line">    <span class="type">char</span> data[<span class="number">5</span>];</span><br><span class="line">    <span class="type">int</span> recv_len = <span class="number">0</span>;</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">for</span>(;;) &#123;</span><br><span class="line">        </span><br><span class="line">        <span class="comment">//data 大小为5，所以每次最多读取 5 字节</span></span><br><span class="line">        recv_len = xStreamBufferReceive(sbuffer, data, <span class="keyword">sizeof</span>(data), pdMS_TO_TICKS(<span class="number">1000</span>));</span><br><span class="line">        SEGGER_RTT_printf(<span class="number">0</span>, <span class="string">&quot;%d bytes received\n&quot;</span>, recv_len);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>main 函数代码：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&quot;FreeRTOS.h&quot;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&quot;task.h&quot;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&quot;stream_buffer.h&quot;</span></span></span><br><span class="line"></span><br><span class="line"><span class="type">int</span> <span class="title function_">main</span><span class="params">(<span class="type">void</span>)</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 创建一个stream buffer，最多可以放 20字节。</span></span><br><span class="line">    <span class="comment">// xTriggerLevelBytes=1，表示只要向stream buffer发送了大于等于1字节的数据，</span></span><br><span class="line">    <span class="comment">// 之前由于stream buffer为空，而处于阻塞态，等待数据的读数据任务，会被立刻唤醒，恢复就绪。</span></span><br><span class="line">    StreamBufferHandle_t sbuffer= xStreamBufferCreate(<span class="number">20</span>,<span class="number">1</span>);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span>(<span class="literal">NULL</span> != sbuffer) &#123;</span><br><span class="line">        </span><br><span class="line">        <span class="keyword">if</span> (pdPASS == xTaskCreate(task_a, <span class="string">&quot;task_a&quot;</span>, <span class="number">100</span>, sbuffer, <span class="number">1</span>, <span class="literal">NULL</span>)</span><br><span class="line">            &amp;&amp; pdPASS == xTaskCreate(task_b, <span class="string">&quot;task_b&quot;</span>, <span class="number">100</span>, sbuffer, <span class="number">1</span>, <span class="literal">NULL</span>))&#123;</span><br><span class="line">            </span><br><span class="line">            SEGGER_RTT_printf(<span class="number">0</span>, <span class="string">&quot;start FreeRTOS\n&quot;</span>);</span><br><span class="line">            vTaskStartScheduler();</span><br><span class="line">        &#125; </span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 正常启动后不会运行到这里</span></span><br><span class="line">    SEGGER_RTT_printf(<span class="number">0</span>, <span class="string">&quot;insufficient resource\n&quot;</span>);</span><br><span class="line">    <span class="keyword">for</span>( ;; );</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;    </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>运行结果：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">start FreeRTOS</span><br><span class="line">sent 9 bytes!</span><br><span class="line">5 bytes received        # 由于用来存所读数据的buffer只有5字节，因此每次最多读取5字节</span><br><span class="line">4 bytes received</span><br><span class="line">sent 9 bytes!</span><br><span class="line">5 bytes received</span><br><span class="line">4 bytes received</span><br></pre></td></tr></table></figure>

<p>我们在 <code>task_b</code> 任务中加一个delay，让其消费变慢，使得写入方每次不能写完：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">void</span> <span class="title function_">task_b</span><span class="params">( <span class="type">void</span> *pvParameters )</span> &#123;</span><br><span class="line">    </span><br><span class="line">    StreamBufferHandle_t sbuffer = (StreamBufferHandle_t)pvParameters;</span><br><span class="line">    <span class="type">char</span> data[<span class="number">5</span>];</span><br><span class="line">    <span class="type">int</span> recv_len = <span class="number">0</span>;</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">for</span>(;;) &#123;</span><br><span class="line">        </span><br><span class="line">        <span class="comment">//data 大小为5，所以每次最多读取 5 字节</span></span><br><span class="line">        recv_len = xStreamBufferReceive(sbuffer, data, <span class="keyword">sizeof</span>(data), pdMS_TO_TICKS(<span class="number">1000</span>));</span><br><span class="line">        SEGGER_RTT_printf(<span class="number">0</span>, <span class="string">&quot;%d bytes received\n&quot;</span>, recv_len);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 让数据消费变慢</span></span><br><span class="line">        vTaskDelay(pdMS_TO_TICKS(<span class="number">3000</span>));</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>重新编译运行结果如下：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">start FreeRTOS</span><br><span class="line">sent 9 bytes!       # stream buffer 被写入了9 字节，还剩11 字节空闲空间</span><br><span class="line">5 bytes received    # 被读取了5 字节，还剩16 字节空间</span><br><span class="line">sent 9 bytes!       # 被写入了9 字节，还剩7 字节空闲空间</span><br><span class="line">5 bytes received    # 被读取了5 字节，还剩12 字节空间</span><br><span class="line">sent 7 bytes!       # 由于任务调度的原因，本次可写入空间的判断依据还停留在上一次判断，认为还剩7 字节空闲空间，因此只写了 7 字节。</span><br><span class="line">                    # 而实际有12 字节，本次写入后，还剩5 字节空间。</span><br><span class="line">sent 5 bytes!       # 只剩5字节空间，因此实际只写了5 字节，还剩0 字节空闲空间</span><br><span class="line">5 bytes received    # 在这之后，由于消费慢，并且每次只取5 字节，</span><br><span class="line">                    # 所以后续的每次发送，只能发送5字节</span><br><span class="line">sent 5 bytes!</span><br><span class="line">5 bytes received</span><br><span class="line">sent 5 bytes!</span><br><span class="line">sent 0 bytes!</span><br><span class="line">5 bytes received</span><br><span class="line">sent 5 bytes!</span><br><span class="line">5 bytes received</span><br><span class="line">sent 5 bytes!</span><br><span class="line">sent 0 bytes!</span><br></pre></td></tr></table></figure>
<br>
ps：需要注意文章代码中的日志输出函数，产品代码中如果需要使用的话，需要考虑线程安全性（多任务安全性），因为中断/任务切换可能发生在另一个任务正在输出日志但还未输出完的时候，这就可能造成日志错乱






    </div>

    
    
    

    <footer class="post-footer">
          

<div class="post-copyright">
<ul>
  <li class="post-copyright-author">
      <strong>本文作者： </strong>feng xun
  </li>
  <li class="post-copyright-link">
      <strong>本文链接：</strong>
      <a href="http://fengxun2017.github.io/2023/02/22/FreeRTOS-stream-buffer/" title="FreeRTOS-stream buffer">http://fengxun2017.github.io/2023/02/22/FreeRTOS-stream-buffer/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh" rel="noopener" target="_blank"><i class="fab fa-fw fa-creative-commons"></i>BY-NC-SA</a> 许可协议。转载请注明出处！
  </li>
</ul>
</div>


        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/2023/02/18/memory-ordering-storebuffer-invalidatequeue/" rel="prev" title="Memory Barriers 和 store buffers、invalidate queues">
                  <i class="fa fa-chevron-left"></i> Memory Barriers 和 store buffers、invalidate queues
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/2023/03/04/FreeRTOS-stream-buffer-details/" rel="next" title="FreeRTOS-stream buffer内部细节">
                  FreeRTOS-stream buffer内部细节 <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 
  <span itemprop="copyrightYear">2025</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">feng xun</span>
</div>
<div class="wordcount">
  <span class="post-meta-item">
    <span class="post-meta-item-icon">
      <i class="fa fa-chart-line"></i>
    </span>
      <span>站点总字数：</span>
    <span title="站点总字数">552k</span>
  </span>
  <span class="post-meta-item">
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
      <span>站点阅读时长 &asymp;</span>
    <span title="站点阅读时长">11:30</span>
  </span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/muse/" rel="noopener" target="_blank">NexT.Muse</a> 强力驱动
  </div>

    </div>
  </footer>

  
  <script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.1/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
<script src="/js/comments.js"></script><script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/schemes/muse.js"></script><script src="/js/next-boot.js"></script>

  





  





</body>
</html>
